<?php
/*
 * code to add project 
*/
session_start();
if(!isset($_SESSION['userid'])){
	header('location:login.php');
}
else
{
	// Create connection
	include("../inc_files/utils/dbconnection.php");
	//generate a new projectID
	$query="SELECT ProjectID FROM projects ORDER BY ProjectID DESC LIMIT 1;";
	$mysqli->query($query) or die($mysqli->error);
	//execute the query
	$projectid="";
	if($stmt = $mysqli -> prepare($query))	{
		$result = $stmt -> execute();
		$stmt -> store_result();
		$stmt -> bind_result($projectid);
		$stmt -> fetch();
		$stmt -> close();
	}

	/*get the next ProjectID in the sequence
	 *e.g. if ACME00123 was the last highest
	* projectID then choose ACME00124
	*/
	if($projectid == "")
	{
		//this is the first project - Query returned no previous projects
		$projectid = "ACME00001";
	} else {
		$sequencenumber = substr($projectid, 4);
		$sequencenumber ++;
		$projectid = "ACME".sprintf('%05d', $sequencenumber);
	}
	//sanitise the input data
	$customerID = $mysqli->real_escape_string($_POST['customerid']);
	$projectManager = $mysqli->real_escape_string($_POST['projectmanager']);
	$projectTitle = $mysqli->real_escape_string($_POST['title']);
	$projectDescription = $mysqli->real_escape_string($_POST['projectdescription']);

	//format the dates
	$startDate = formatdate(trim($_POST['startdate']));
	$endDate = formatdate(trim($_POST['enddate']));


	// insert the customer details into the database

	$query="INSERT INTO projects (ProjectID, CustomerID, StartDate, EndDate, ProjectManager, ProjectTitle, ProjectDescription)
	VALUES
	('$projectid','$customerID','$startDate','$endDate','$projectManager','$projectTitle','$projectDescription')";

	$mysqli->query($query) or die($mysqli->error);

	//add default top-level task
	$TaskTitle = "Top Level";
	$TaskDescription = "General project work";

	$query="INSERT INTO tasks (Project, Title, StartDate, EndDate, Budget, Description, Deleted, PercentComplete)
	VALUES
	('$projectid','$TaskTitle','$startDate','$endDate',0,'$TaskDescription', 2, 0)";  //deleted value of 2 - deletion disabled

	$mysqli->query($query) or die($mysqli->error);

	//tidy up database connection
	$mysqli->close();

	//redirect the page to add project tasks
	header("Location:editproject.php?projectid=".$projectid);




}

//function to convert dates from dates entered by the user
//to dates for MySQL
function formatdate($date){
	$datearray = explode('/' , $date);
	$date = $datearray[2].'-'.$datearray[1].'-'.$datearray[0];
	return $date;

}
?>


